package com.example.beauty.contact;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
//import android.widget.SearchView;
import android.widget.Toast;

import com.example.beauty.db.gen.Note;
import com.example.beauty.db.gen.NoteDao;
import com.example.beauty.contact.SearchView;

import java.util.ArrayList;
import java.util.List;

public class ContactMain extends AppCompatActivity implements
        com.example.beauty.contact.SearchView.SearchViewListener{

    private ListView listView;
    private NoteDao main_noteDao;
    private GreenDaoManager main_initDao;
    private NoteAdapter adapter;
    private Note datanote;  //传递给下一个活动的note

    /****************自定义searchView分界线*****************/
    /**
     * 搜索结果列表view
     */
    private ListView lvResults;

    /**
     * 搜索view
     */
    private SearchView searchView;

    /**
     * 图片返回按钮
     */
    private ImageButton imagebtn;

    /**
     * 热搜框列表adapter
     */
    private ArrayAdapter<String> hintAdapter;

    /**
     * 自动补全列表adapter
     */
    private ArrayAdapter<String> autoCompleteAdapter;

    /**
     * 搜索结果列表adapter
     */
    private NoteAdapter resultAdapter;

    /**
     * 数据库数据，总数据
     */
    private List<Note> dbData;

    /**
     * 热搜版数据
     */
    private List<String> hintData;

    /**
     * 搜索过程中自动补全数据
     */
    private List<String> autoCompleteData;

    /**
     * 搜索结果的数据
     */
    private List<Note> resultData;

    /**
     * 默认提示框显示项的个数
     */
    private static int DEFAULT_HINT_SIZE = 4;

    /**
     * 提示框显示项的个数
     */
    private static int hintSize = DEFAULT_HINT_SIZE;

    /**
     * 设置提示框显示项的个数
     *
     * @param hintSize 提示框显示个数
     */
    public static void setHintSize(int hintSize) {
        ContactMain.hintSize = hintSize;
    }

    /****************自定义searchView分界线*****************/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_main);

        /*初始化GreenDao框架的数据库,数据库名为Info*/
        main_initDao.InitDao(ContactMain.this,"Info.db");
        main_noteDao = GreenDaoManager.getDaoSession().getNoteDao();
        /****************自定义searchView分界线*****************/
        initData();
        initViews();
        /****************自定义searchView分界线*****************/

        listView = (ListView) findViewById(R.id.list_view);
        /*查询数据库Info的表格*/
        List<Note> list = main_noteDao.queryBuilder().list();
        for (int i = 0; i < list.size(); i++) {
            Log.d("google_lenve", "search: " + list.get(i).toString());
        }

        adapter = new NoteAdapter(ContactMain.this,R.layout.note_item,list);
        /*辨别适配器内容有没有改变*/
        adapter.notifyDataSetChanged();
        listView.setAdapter(adapter);
        /*文本过滤*/
        listView.setTextFilterEnabled(true);
        /*设置listView的item点击响应事件*/
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //传递数据，把点击的Item的Note对象传递给EditContact
                Intent intent = new Intent(ContactMain.this,EditContact.class);
                Bundle bundle_note =new Bundle();
                datanote = new Note();
                datanote = (Note)adapter.getItem(position);
                bundle_note.putLong("datanoteId",datanote.getId());
                bundle_note.putString("datanoteName",datanote.getName());
                bundle_note.putString("datanotePhone",datanote.getPhone());
                /*传递id给EditContact*/
                intent.putExtras(bundle_note);
                /*注意：id从0开始*/
                Log.i("ContactMain","tht note name in Edit is:"+datanote.getName());
                Log.i("ContactMain","tht note phone in Edit is:"+datanote.getPhone());
                Log.i("ContactMain","tht note id in Edit is:"+datanote.getId());
                startActivity(intent);
            }
        });

        /*监听搜索文本*/
        searchView.setOnQueryTextListener(new android.widget.SearchView.OnQueryTextListener() {
            // 当点击搜索按钮时触发该方法
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            // 当搜索内容改变时触发该方法
            @Override
            public boolean onQueryTextChange(String newText) {
                if (!TextUtils.isEmpty(newText)){
                    listView.setFilterText(newText);
                }else{
                    listView.clearTextFilter();
                }
                return false;
            }
        });
    }

    /*增加菜单，并显示菜单*/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        /*inflate()有两个参数，第一个指通过那个资源文件创建菜单，
        * 第二个指菜单项添加到哪个Menu对象*/
        getMenuInflater().inflate(R.menu.contact_main_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    /*添加菜单项相应事件*/
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.add_item:
                /*此处添加Add菜单项相应事件*/
                /*Toast.makeText(this,"clicked Add Menu!",Toast.LENGTH_SHORT).show();*/
                Intent intent = new Intent(ContactMain.this,EditContact.class);
                Bundle bundle_note =new Bundle();
                bundle_note.putString("datanoteName","");
                bundle_note.putString("datanotePhone","");
                /*传递id给EditContact*/
                intent.putExtras(bundle_note);
                Log.i("ContactMain","tht note name in Edit is: Null");
                Log.i("ContactMain","tht note phone in Edit is: Null");
                startActivity(intent);
                break;
            case R.id.exit_item:
                this.finish();
            default:Log.i("ContactMain","there was wrong with clicl Add Menu!");
        }
        return super.onOptionsItemSelected(item);
    }

    /*主活动采用SingleTask模式*/
    @Override
    protected void onRestart()
    {
        super.onRestart();
        Log.d("ContactMain","onRestart!");
    }

    /****************自定义searchView分界线*****************/
    /**
     * 初始化视图
     */
    private void initViews() {
        lvResults = (ListView) findViewById(R.id.main_lv_search_results);
        searchView = (SearchView) findViewById(R.id.main_search_layout);
        /*//把主界面的listView传进来
        searchView.setListView(listView);*/

        //设置监听
        searchView.setSearchViewListener(this);

        //设置adapter
        //searchView.setTipsHintAdapter(hintAdapter);
        searchView.setAutoCompleteAdapter(autoCompleteAdapter);

        lvResults.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                /*Toast.makeText(ContactMain.this, position + "", Toast.LENGTH_SHORT).show();*/
                listView.setVisibility(View.GONE);
                Intent intent = new Intent(ContactMain.this,EditContact.class);
                Bundle bundle_note =new Bundle();
                datanote = new Note();
                //datanote = (Note)adapter.getItem(position);
                datanote = (Note)resultAdapter.getItem(position);
                bundle_note.putLong("datanoteId",datanote.getId());
                bundle_note.putString("datanoteName",datanote.getName());
                bundle_note.putString("datanotePhone",datanote.getPhone());
                /*传递id给EditContact*/
                intent.putExtras(bundle_note);
                /*注意：id从0开始*/
                Log.i("ContactMain","tht note name in Edit is:"+datanote.getName());
                Log.i("ContactMain","tht note phone in Edit is:"+datanote.getPhone());
                Log.i("ContactMain","tht note id in Edit is:"+datanote.getId());
                startActivity(intent);
            }
        });
    }

    /**
     * 初始化数据
     */
    private void initData() {
        //从数据库获取数据
        getDbData();
        //初始化热搜版数据
        //getHintData();
        //初始化自动补全数据
        getAutoCompleteData(null);
        //初始化搜索结果数据
        getResultData(null);
    }

    /**
     * 获取db 数据
     */
    private void getDbData() {
        List<Note> list_db= main_noteDao.queryBuilder().list();
        dbData = new ArrayList<>(list_db.size());
        for (int i = 0; i < list_db.size(); i++) {
            //dbData.add(new Note(R.drawable.icon, "android开发必备技能" + (i + 1), "Android自定义view——自定义搜索view", i * 20 + 2 + ""));
            //向容器List添加元素，获取全部记录
            dbData.add(list_db.get(i));
        }
    }

    /**
     * 获取热搜版data 和adapter
     */
    /*private void getHintData() {
        hintData = new ArrayList<>(hintSize);
        for (int i = 1; i <= hintSize; i++) {
            hintData.add("热搜版" + i + "：Android自定义View");
        }
        hintAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, hintData);
    }

    /**
     * 获取自动补全data 和adapter
     */
    private void getAutoCompleteData(String text) {
        if (autoCompleteData == null) {
            //初始化
            autoCompleteData = new ArrayList<>(hintSize);
        } else {
            // 根据text 获取auto data
            autoCompleteData.clear();
            for (int i = 0, count = 0; i < dbData.size()
                    && count < hintSize; i++) {
                if (dbData.get(i).getName().contains(text.trim())) {
                    autoCompleteData.add(dbData.get(i).getName());
                    count++;
                }
            }
        }
        if (autoCompleteAdapter == null) {
            autoCompleteAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, autoCompleteData);
        } else {
            autoCompleteAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 获取搜索结果data和adapter
     */
    private void getResultData(String text) {
        if (resultData == null) {
            // 初始化
            resultData = new ArrayList<>();
        } else {
            resultData.clear();
            for (int i = 0; i < dbData.size(); i++) {
                if (dbData.get(i).getName().contains(text.trim())) {
                    resultData.add(dbData.get(i));
                }
            }
        }
        if (resultAdapter == null) {
            resultAdapter = new NoteAdapter(this, R.layout.note_item, resultData);
        } else {
            resultAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 当搜索框 文本改变时 触发的回调 ,更新自动补全数据
     * @param text
     */
    @Override
    public void onRefreshAutoComplete(String text) {
        //更新数据
        getAutoCompleteData(text);
    }

    /**
     * 点击搜索键时edit text触发的回调
     *
     * @param text
     */
    @Override
    public void onSearch(String text) {
        //更新result数据
        getResultData(text);
        lvResults.setVisibility(View.VISIBLE);
        listView.setVisibility(View.INVISIBLE);
        //第一次获取结果 还未配置适配器
        if (lvResults.getAdapter() == null) {
            //获取搜索数据 设置适配器
            lvResults.setAdapter(resultAdapter);
        } else {
            //更新搜索数据
            resultAdapter.notifyDataSetChanged();
        }
        Toast.makeText(this, "完成搜索", Toast.LENGTH_SHORT).show();
    }
    /****************自定义searchView分界线*****************/

}
